package io.zhengsh.juc._0jmm;

/**
 * 指令重排序 BUG 测试代码
 */
public class MemoryReorderingTest{

    public static void main(String[] args) throws Exception {

        while (true) {

            Counter counter = new Counter();

            Thread t1 = new Thread(() -> {
                counter.a = 1;
                counter.i = counter.b;
            }, "线程1");

            Thread t2 = new Thread(() -> {
                counter.b = 1;
                counter.j = counter.a;
            }, "线程2");

            t1.start();
            t2.start();

            // 使用join是为了让t1和t2线程先执行完成之后,main线程再判断i和j是否等于0
            t1.join();
            t2.join();

            if (counter.i == 0 && counter.j == 0) {
                break;
            }
        }
    }
}

class Counter {

    public int a = 0, b = 0;
    public int i = 0, j = 0;

}